﻿using MediatR;
using System.Collections.Generic;
using Traceability.App.API.Application.Command.Basic;
using Traceability.App.Domain.Entities;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructure.Interface;

namespace Traceability.App.API.Application.Handler.Basic
{
    /// <summary>
    /// 删除溯源基本信息请求命令处理类
    /// </summary>
    public class DeleteBasic_TraceabilityHandler:IRequestHandler<DeleteBasic_TraceabilityCommand,ApiResult<int>>
    {
        IBaseRepository<Basic_Traceability> basicRep;

        public DeleteBasic_TraceabilityHandler(IBaseRepository<Basic_Traceability> basicRep)
        {
            this.basicRep = basicRep;
        }

        public Task<ApiResult<int>> Handle(DeleteBasic_TraceabilityCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var nodes=request.production_Batchlist.Split(',').ToList();
                int r = 0;
                foreach (var node in nodes)
                {
                    var list = basicRep.GetAll().Where(x => x.Production_Batch == node&&!x.IsDeleted).FirstOrDefault();
                    if(list!=null)
                    {
                        list.IsDeleted = true;
                        r = basicRep.UpdateAsync(list).Result;
                    }
                    
                }
                if (r > 0)
                {
                    res.Msg = "删除成功";
                    res.Code = ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "删除失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);


            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
